package com.friend.chat.media.pressAudio

import android.content.Context
import android.media.AudioManager
import android.media.MediaRecorder
import java.io.File

/**
 * @des
 * @author batie fancy
 * @date 2023/2/27
 */
interface IRecorderManger {
    /**
     * 开始录制
     */
    fun start()

    /**
     * 获取语音文件路径
     */
    fun getFilePath(): File?

    /**
     * 获取录制时长
     */
    fun getRecordDuration(): Long

    /**
     * 停止录制
     */
    fun stop()

    /**
     * 当前是否正在录制中
     */
    fun isRecording(): Boolean

    /**
     * 返回音量比例 范围 0 - 1
     */
    fun getVolumeProportion(): Double
}
class PressAudioRecorderManager(private val context: Context):IRecorderManger {
    private val AUDIO_PATH =context.cacheDir.path+"/test.amr"

    private var mediaRecorder: MediaRecorder? = null
    private val audioManager: AudioManager =
        context.applicationContext.getSystemService(
            Context.AUDIO_SERVICE
        ) as AudioManager
    private var filePath: File? = null
    private var startTime = 0L
    private var endTime = 0L
    private var mIsRecording:Boolean =false


    init {
        mediaRecorder = MediaRecorder()
        mediaRecorder?.setOutputFile(AUDIO_PATH)
        mediaRecorder?.setAudioSource(MediaRecorder.AudioSource.MIC)//音频源来自麦克风
        mediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB)
        mediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
        val  file = File(AUDIO_PATH)
        file.deleteOnExit()
    }

    /**
     * 开始录制
     */
    override fun start() {
      if (!mIsRecording){
          mediaRecorder?.prepare()
          mediaRecorder?.start()
          mIsRecording = true
      }
    }

    override fun stop() {
        if (mIsRecording){
            mediaRecorder?.stop()
            mediaRecorder?.release()
            mIsRecording = false
        }
    }


    override fun getFilePath(): File {
        return File(AUDIO_PATH)
    }

    override fun getRecordDuration(): Long {
        return System.currentTimeMillis() - startTime
    }


    override fun isRecording(): Boolean {
        return mIsRecording
    }

    override fun getVolumeProportion(): Double {
        if (!mIsRecording){
            return 0.0
        }
        if (mediaRecorder == null){
            return 0.0
        }else{
            return mediaRecorder!!.maxAmplitude.toDouble()
        }
    }

}